/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package xmlutils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import org.xml.sax.SAXException;

/**
 *
 * @author tiwtiger
 */
public class PDFGenerating {

    public static boolean createPDF(File inputFile, File outputFile, String realPath) {
        OutputStream output = null;
        try {
            FopFactory fopFactory = FopFactory.newInstance();
//            fopFactory.setBaseURL(realPath);
            FOUserAgent foUserAgent = fopFactory.newFOUserAgent();
//            foUserAgent.setBaseURL(fopFactory.getBaseURL());

            File config = new File(realPath + "web/xsl/myconfig.xconf");
            fopFactory.setUserConfig(config);

            output = new BufferedOutputStream(new FileOutputStream(outputFile));
            Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, output);

            TransformerFactory factory = TransformerFactory.newInstance();
            Transformer transformer = factory.newTransformer();
            Source src = new StreamSource(inputFile);
            Result res = new SAXResult(fop.getDefaultHandler());

            transformer.transform(src, res);
            return true;
        } catch (TransformerException ex) {
            Logger.getLogger(PDFGenerating.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (SAXException ex) {
            Logger.getLogger(PDFGenerating.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        } catch (IOException ex) {
            Logger.getLogger(PDFGenerating.class.getName()).log(Level.SEVERE, null, ex);
            return false;
        }finally{
            try{
                output.close();
            }catch(IOException ex){
                Logger.getLogger(PDFGenerating.class.getName()).log(Level.SEVERE, null, ex);
                return false;
            }
        }
    }
}
